package top.qingyunge.autumn.util;

import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

public class EnumGenerator {
    public static Class<?> createEnum(String packageName, String enumClassName, List<String> enumValues) throws Exception {
        String enumTemplate=packageName+"\n;public enum %s { %s }";
        String enumBody =String.join(",",enumValues);
        String enumSource = String.format(enumTemplate, enumClassName, enumBody);
        //            1 动态编译枚举类
        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
        StandardJavaFileManager fileManager =
                compiler.getStandardFileManager(null, null, null);
        // 写入临时文件
        String tmpEnumFilePath= String.format("%s.java",enumClassName);
        Path path = Paths.get(tmpEnumFilePath);
        Files.write(path,enumSource.getBytes());
        //         编译临时文件
        Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjectsFromStrings(List.of(tmpEnumFilePath));
        compiler.getTask(null,fileManager, null,null,null,compilationUnits).call();
        fileManager.close();
        Files.deleteIfExists(path);

        return Class.forName(enumClassName);
    }

    // 枚举类加载器
    private static class EnumClassLoader extends ClassLoader {
        public Class<?> defineClass(String name, byte[] b) {
            return defineClass(name, b, 0, b.length);
        }
    }
}